<template>
  <div class="searchWrapper">
    <div class="searchBox">
      <form action="/">
        <van-search
          background="rgb(26, 138, 230)"
          v-model="value"
          show-action
          placeholder="请输入搜索关键词"
          @cancel="onCancel"
          @search="onSearch"
          @input="inpChange()"
        >
          <template #action>
            <div @click="onCancel">取消</div>
          </template>
        </van-search>
      </form>
    </div>
    <!-- 搜索联想 -->
    <search-hint
      :vlaues="value"
      v-if="view === 1"
      @search="onSearch($event)"
    ></search-hint>
    <!-- 搜索结果 -->
    <results v-else-if="view === 2" :resultData="resultData"></results>
    <!-- 搜索历史 -->
    <history v-else @searchHistoryData="startSearch($event)"></history>
  </div>
</template>

<script>
import history from './component/history.vue'
import results from './component/results.vue'
import searchHint from './component/searchHint'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      value: '',
      view: 3, // 显示的视图  1 是搜索联想 2 是搜索结果 3 是搜索历史
      resultData: '',
      historyData: []
    }
  },
  mounted () {},
  methods: {
    async onSearch (data) {
      if (data !== '') {
        // 显示结果视图
        this.view = 2
        this.resultData = data
      }
      // 判断是否登录
      if (this.$store.state.userToken === null) {
        // 没登录存储到本地
        // 判断本地历史记录是否大于6如果大于6就替换掉第一个
        if (getItem('searchHistory') && getItem('searchHistory').length >= 6) {
          let newData = getItem('searchHistory')
          newData.splice(5, 1)
          newData = [data, ...newData]
          setItem('searchHistory', newData)
          // 判断本地是否存在searchHistory以及存储的值是否相等
        } else if (
          getItem('searchHistory') &&
          getItem('searchHistory').indexOf(data) === -1
        ) {
          // 没大于六就添加到后面
          const newData = [data, ...getItem('searchHistory')]
          setItem('searchHistory', newData)
        } else if (!getItem('searchHistory')) {
          const initData = [data]
          setItem('searchHistory', initData)
        } else {
        }
      }
    },
    // 点击历史是搜索历史
    startSearch (data) {
      this.onSearch(data)
      this.value = data
    },
    onCancel () {
      this.$router.back(-1)
    },
    inpChange () {
      if (this.value === '') {
        this.view = 3
      } else {
        this.view = 1
      }
    }
  },
  components: { searchHint, history, results }
}
</script>

<style lang="less" scoped>
.searchBox {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
}
.searchWrapper {
  background-color: #fff;
  width: 100%;
  height: 100vh;
  padding-top: 120px;
  .van-search__action {
    background-color: unset;
    color: #fff;
  }
}
</style>
